<template>
  <div class="profile">
    <div class="page-header">
      <h2>个人中心</h2>
    </div>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-info">
            <div class="avatar-section">
              <el-avatar :size="80" :src="userInfo.avatar">
                {{ userInfo.realName ? userInfo.realName.charAt(0) : 'U' }}
              </el-avatar>
              <div class="user-basic">
                <h3>{{ userInfo.realName || userInfo.username }}</h3>
                <p class="user-role">
                  <el-tag
                    v-for="role in userRoles"
                    :key="role"
                    :type="getRoleType(role)"
                    size="small"
                  >
                    {{ getRoleText(role) }}
                  </el-tag>
                </p>
              </div>
            </div>

            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-number">{{ stats.totalProjects }}</div>
                <div class="stat-label">总项目数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ stats.totalPapers }}</div>
                <div class="stat-label">论文数量</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ stats.pendingAudits }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="text" @click="editMode = !editMode">
                {{ editMode ? '取消编辑' : '编辑信息' }}
              </el-button>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            :disabled="!editMode"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="form.realName" placeholder="请输入真实姓名" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学号/工号" prop="studentId">
                  <el-input v-model="form.studentId" placeholder="请输入学号或工号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属院系" prop="department">
                  <el-input v-model="form.department" placeholder="请输入所属院系" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="专业" prop="major">
                  <el-input v-model="form.major" placeholder="请输入专业" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年级" prop="grade">
                  <el-input v-model="form.grade" placeholder="请输入年级" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="form.bio"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>

            <el-form-item v-if="editMode">
              <el-button type="primary" @click="handleSave" :loading="saving">
                保存
              </el-button>
              <el-button @click="handleCancel">
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <span>安全设置</span>
      </template>
      <el-button type="primary" @click="passwordDialogVisible = true">
        修改密码
      </el-button>
    </el-card>

    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api/user'

export default {
  name: 'Profile',
  setup() {
    const store = useStore()

    const formRef = ref()
    const passwordFormRef = ref()
    const editMode = ref(false)
    const saving = ref(false)
    const passwordDialogVisible = ref(false)
    const changingPassword = ref(false)

    const userInfo = computed(() => store.getters.userInfo)
    const userRoles = computed(() => store.getters.roles)

    const stats = ref({
      totalProjects: 0,
      totalPapers: 0,
      pendingAudits: 0
    })

    const form = reactive({
      username: '',
      realName: '',
      email: '',
      phone: '',
      studentId: '',
      department: '',
      major: '',
      grade: '',
      bio: ''
    })

    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    const rules = reactive({
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    })

    const passwordRules = reactive({
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    })

    const loadUserProfile = async () => {
      try {
        const response = await userAPI.getProfile()
        const profile = response.data

        // 手动映射字段，确保数据正确绑定
        form.username = profile.username || ''
        form.realName = profile.realName || ''
        form.email = profile.email || ''
        form.phone = profile.phone || ''
        form.studentId = profile.studentId || profile.teacherId || ''
        form.department = profile.department || ''
        form.major = profile.major || ''
        form.grade = profile.grade || ''
        form.bio = profile.bio || ''

        // 加载统计数据
        stats.value = {
          totalProjects: profile.totalProjects || 0,
          totalPapers: profile.totalPapers || 0,
          pendingAudits: profile.pendingAudits || 0
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
      }
    }

    const handleSave = async () => {
      try {
        await formRef.value.validate()

        saving.value = true
        await userAPI.updateProfile(form)

        // 更新store中的用户信息
        await store.dispatch('user/getUserInfo')

        ElMessage.success('保存成功')
        editMode.value = false
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }

    const handleCancel = () => {
      editMode.value = false
      loadUserProfile() // 重新加载数据
    }

    const handleChangePassword = async () => {
      try {
        await passwordFormRef.value.validate()

        changingPassword.value = true
        await userAPI.changePassword(passwordForm)

        ElMessage.success('密码修改成功')
        passwordDialogVisible.value = false

        // 重置表单
        Object.keys(passwordForm).forEach(key => {
          passwordForm[key] = ''
        })
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      } finally {
        changingPassword.value = false
      }
    }

    const getRoleText = (role) => {
      const roleMap = {
        ADMIN: '管理员',
        TEACHER: '教师',
        STUDENT: '学生'
      }
      return roleMap[role] || role
    }

    const getRoleType = (role) => {
      const typeMap = {
        ADMIN: 'danger',
        TEACHER: 'warning',
        STUDENT: 'success'
      }
      return typeMap[role] || 'info'
    }

    onMounted(() => {
      loadUserProfile()
    })

    return {
      formRef,
      passwordFormRef,
      editMode,
      saving,
      passwordDialogVisible,
      changingPassword,
      userInfo,
      userRoles,
      stats,
      form,
      passwordForm,
      rules,
      passwordRules,
      handleSave,
      handleCancel,
      handleChangePassword,
      getRoleText,
      getRoleType
    }
  }
}
</script>

<style lang="scss" scoped>
.profile {
  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .profile-card {
    .profile-info {
      text-align: center;

      .avatar-section {
        margin-bottom: 30px;

        .user-basic {
          margin-top: 16px;

          h3 {
            margin: 0 0 8px 0;
            color: #303133;
          }

          .user-role {
            margin: 0;

            .el-tag {
              margin-right: 8px;
            }
          }
        }
      }

      .user-stats {
        display: flex;
        justify-content: space-around;
        padding-top: 20px;
        border-top: 1px solid #f0f0f0;

        .stat-item {
          .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #409eff;
            line-height: 1;
          }

          .stat-label {
            font-size: 12px;
            color: #909399;
            margin-top: 4px;
          }
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
